<template>
  <div class="container fade-in">
    <!-- 页面头部 -->
    <div class="header">
      <div class="breadcrumb">
        <router-link to="/coupon-packages" class="breadcrumb-link">优惠券包管理</router-link>
        <span class="breadcrumb-separator">></span>
        <span class="breadcrumb-current">{{ isEdit ? '编辑优惠券包' : '创建优惠券包' }}</span>
      </div>
      <div class="actions">
        <button class="btn secondary" @click="goBack">
          <span class="icon" v-html="'←'"></span>
          返回
        </button>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <div class="spinner"></div>
      <p>{{ isEdit ? '加载优惠券包信息中...' : '初始化中...' }}</p>
    </div>

    <div v-else class="content">
      <form @submit.prevent="noop" class="form-container">
        <!-- 基本信息 -->
        <div class="card slide-up" style="animation-delay: 0.1s">
          <div class="card-header">
            <h3>基本信息</h3>
          </div>
          <div class="card-content">
            <div class="form-grid">
              <div class="form-group">
                <label class="required">优惠券包名称</label>
                <input
                  v-model="form.name"
                  type="text"
                  class="form-input"
                  placeholder="请输入优惠券包名称"
                  required
                  maxlength="100"
                />
                <div class="form-hint">建议使用简洁明了的名称，方便用户识别</div>
              </div>
              
              <div class="form-group">
                <label>生效时间</label>
                <DateField v-model="advanced.startTimeLocal" mode="datetime" />
                <div class="form-hint">优惠券包开始生效的时间</div>
              </div>

              <div class="form-group">
                <label>失效时间</label>
                <DateField v-model="advanced.endTimeLocal" mode="datetime" />
                <div class="form-hint">优惠券包失效的时间</div>
              </div>

              <div class="form-group">
                <label>状态</label>
                <select v-model.number="advanced.status" class="form-input">
                  <option :value="1">草稿</option>
                  <option :value="2">已发布</option>
                  <option :value="3">已停用</option>
                </select>
                <div class="form-hint">后端可编辑的券包状态</div>
              </div>

              <div class="form-group">
                <label>启用状态</label>
                <select v-model.number="advanced.enableStatus" class="form-input">
                  <option :value="1">启用</option>
                  <option :value="0">禁用</option>
                </select>
                <div class="form-hint">控制券包是否启用</div>
              </div>

              <div class="form-group full-width">
                <label>二维码地址（可选）</label>
                <input
                  v-model="advanced.qrcodeUrl"
                  type="text"
                  class="form-input"
                  placeholder="http(s)://..."
                />
              </div>

              <div class="form-group full-width">
                <label>扩展属性（JSON，可选）</label>
                <textarea
                  v-model="advanced.extraProperties"
                  class="form-textarea"
                  placeholder='{"key":"value"}'
                  rows="3"
                ></textarea>
              </div>

              <div class="form-group">
                <label>商户ID</label>
                <input v-model="advanced.merchantId" type="text" class="form-input" disabled />
              </div>
              
              <div class="form-group full-width">
                <label>描述</label>
                <textarea
                  v-model="form.description"
                  class="form-textarea"
                  placeholder="请输入优惠券包描述（可选）"
                  rows="3"
                  maxlength="500"
                ></textarea>
                <div class="form-hint">详细描述优惠券包的内容和使用说明</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 选择优惠券模板 -->
        <div class="card slide-up" style="animation-delay: 0.2s">
          <div class="card-header">
            <h3>选择优惠券模板</h3>
            <div class="card-actions">
              <button type="button" class="btn secondary sm" @click="loadAvailableTemplates">
                <span class="icon">🔄</span>
                刷新模板
              </button>
            </div>
          </div>
          <div class="card-content">
            <!-- 搜索和筛选 -->
            <div class="template-filters">
              <div class="filter-row">
                <div class="filter-field">
                  <input
                    v-model="templateFilters.name"
                    type="text"
                    class="form-input"
                    placeholder="搜索模板名称"
                    @input="debouncedTemplateSearch"
                  />
                </div>
                <div class="filter-field">
                  <select v-model="templateFilters.couponType" class="form-input" @change="loadAvailableTemplates">
                    <option value="">全部类型</option>
                    <option value="1">减免券</option>
                    <option value="2">折扣券</option>
                    <option value="3">礼品券</option>
                  </select>
                </div>
                <div class="filter-field">
                  <select v-model="templateFilters.isActive" class="form-input" @change="loadAvailableTemplates">
                    <option value="">全部状态</option>
                    <option value="true">启用</option>
                    <option value="false">禁用</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- 已选择的模板 -->
            <div v-if="selectedTemplates.length > 0" class="selected-templates">
              <h4>已选择的模板 ({{ selectedTemplates.length }})</h4>
              <div class="selected-grid">
                <div v-for="template in selectedTemplates" :key="template.id" class="selected-template">
                  <div class="template-info">
                    <div class="template-name">{{ template.name }}</div>
                    <div class="template-type">{{ getCouponTypeText(template.couponType) }}</div>
                  </div>
                  <button
                    type="button"
                    class="btn danger sm"
                    @click="removeTemplate(template.id!)"
                  >
                    移除
                  </button>
                </div>
              </div>
            </div>

            <!-- 可选择的模板列表 -->
            <div class="available-templates">
              <h4>可选择的模板</h4>
              
              <div v-if="templatesLoading" class="loading-state">
                <div class="spinner"></div>
                <p>加载模板中...</p>
              </div>
              
              <div v-else-if="availableTemplates.length === 0" class="empty-state">
                <div class="empty-icon">🎟️</div>
                <h4>暂无可用模板</h4>
                <p>没有找到符合条件的优惠券模板</p>
              </div>
              
              <div v-else class="templates-grid">
                <div
                  v-for="template in availableTemplates"
                  :key="template.id"
                  class="template-card"
                  :class="{ selected: isTemplateSelected(template.id!) }"
                >
                  <div class="template-header">
                    <h5>{{ template.name }}</h5>
                    <div class="template-type">
                      <span :class="['type-badge', getCouponTypeClass(template.couponType)]">
                        {{ getCouponTypeText(template.couponType) }}
                      </span>
                    </div>
                  </div>
                  
                  <div class="template-content">
                    <div class="template-info">
                      <div class="info-row">
                        <span class="label">优惠金额：</span>
                        <span class="value">{{ formatCouponValue(template) }}</span>
                      </div>
                      <div class="info-row">
                        <span class="label">使用门槛：</span>
                        <span class="value">{{ formatThreshold(template.useThresholdAmount) }}</span>
                      </div>
                      <div class="info-row">
                        <span class="label">状态：</span>
                        <span :class="['status', template.isActive ? 'active' : 'inactive']">
                          {{ template.isActive ? '启用' : '禁用' }}
                        </span>
                      </div>
                    </div>
                  </div>
                  
                  <div class="template-actions">
                    <button
                      type="button"
                      class="btn primary sm"
                      :disabled="isTemplateSelected(template.id!)"
                      @click="addTemplate(template)"
                    >
                      {{ isTemplateSelected(template.id!) ? '已选择' : '选择' }}
                    </button>
                  </div>
                </div>
              </div>

              <!-- 分页 -->
              <div v-if="availableTemplates.length > 0" class="pagination">
                <button
                  type="button"
                  class="btn secondary sm"
                  :disabled="templatePagination.pageIndex <= 1"
                  @click="changeTemplatePage(templatePagination.pageIndex - 1)"
                >
                  上一页
                </button>
                <span class="page-info">
                  第 {{ templatePagination.pageIndex }} 页，共 {{ Math.ceil(templatePagination.totalCount / templatePagination.pageSize) }} 页
                </span>
                <button
                  type="button"
                  class="btn secondary sm"
                  :disabled="templatePagination.pageIndex >= Math.ceil(templatePagination.totalCount / templatePagination.pageSize)"
                  @click="changeTemplatePage(templatePagination.pageIndex + 1)"
                >
                  下一页
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 表单操作 -->
        <div class="form-actions slide-up" style="animation-delay: 0.3s">
          <button type="button" class="btn secondary" @click="goBack">取消</button>
          <button
            type="button"
            class="btn primary"
            :disabled="submitting || !isFormValid"
            @click="submitForm"
          >
            <span v-if="submitting" class="spinner-sm"></span>
            {{ submitting ? '保存中...' : (isEdit ? '更新' : '创建') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import DateField from '../components/DateField.vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { getCurrentUser } from '../services/user'
import {
  CouponService,
  type CouponPackage,
  type CouponPackageCreateRequest,
  type CouponPackageUpdateRequest,
  type CouponTemplate,
  type CouponTemplateQueryRequest,
  getCouponTypeText,
  formatCouponAmount,
  formatCouponDiscount
} from '../services/coupon'
import { isSuccess } from '../services/types'

// 原生 JavaScript 实现 debounce
function debounce<T extends (...args: any[]) => any>(func: T, delay: number): (...args: Parameters<T>) => void {
  let timeoutId: ReturnType<typeof setTimeout>
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(null, args), delay)
  }
}

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()

// 响应式数据
const loading = ref(false)
const templatesLoading = ref(false)
const submitting = ref(false)
const availableTemplates = ref<CouponTemplate[]>([])
const selectedTemplates = ref<CouponTemplate[]>([])

// 表单数据
const form = reactive<CouponPackageCreateRequest & { id?: string }>({
  name: '',
  description: '',
  couponTemplateIds: []
})

// 保留后端必填字段，编辑更新时需要原值回传
const backendFields = reactive<{
  status?: number
  enableStatus?: number
  startTime?: string
  endTime?: string
  qrcodeUrl?: string
  extraProperties?: string
  merchantId?: string
}>({})

// 与后端可编辑字段对齐的高级可编辑数据
const advanced = reactive({
  status: undefined as number | undefined,
  enableStatus: undefined as number | undefined,
  startTimeLocal: '' as string,
  endTimeLocal: '' as string,
  qrcodeUrl: '' as string,
  extraProperties: '' as string,
  merchantId: '' as string,
})

// 将显示值（YYYY-MM-DD HH:mm[:ss] 或 带T分隔）转为无时区时间字符串（PostgreSQL timestamp without time zone）
function toLocalTimestamp(dtLocal: string): string {
  if (!dtLocal) return ''
  const m = dtLocal.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?$/)
  if (m) {
    const [, yyyy, mm, dd, hh, min, ss] = m
    return `${yyyy}-${mm}-${dd}T${hh}:${min}:${ss || '00'}`
  }
  try {
    const d = new Date(dtLocal)
    const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`)
    const yyyy = d.getFullYear()
    const mm = pad(d.getMonth() + 1)
    const dd = pad(d.getDate())
    const hh = pad(d.getHours())
    const min = pad(d.getMinutes())
    const ss = pad(d.getSeconds())
    return `${yyyy}-${mm}-${dd}T${hh}:${min}:${ss}`
  } catch {
    return ''
  }
}

function nowLocalTimestamp(offsetMs = 0): string {
  const d = new Date(Date.now() + offsetMs)
  const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`)
  const yyyy = d.getFullYear()
  const mm = pad(d.getMonth() + 1)
  const dd = pad(d.getDate())
  const hh = pad(d.getHours())
  const min = pad(d.getMinutes())
  const ss = pad(d.getSeconds())
  return `${yyyy}-${mm}-${dd}T${hh}:${min}:${ss}`
}

function toLocalInputValue(iso?: string): string {
  if (!iso) return ''
  try {
    const d = new Date(iso)
    const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`)
    const yyyy = d.getFullYear()
    const mm = pad(d.getMonth() + 1)
    const dd = pad(d.getDate())
    const hh = pad(d.getHours())
    const min = pad(d.getMinutes())
    const ss = pad(d.getSeconds())
    // 供 DateField 显示的中文格式（不带 T）
    return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}`
  } catch {
    return ''
  }
}

// 模板筛选条件
const templateFilters = reactive({
  name: '',
  couponType: '' as string,
  isActive: '' as string
})

// 模板分页信息
const templatePagination = reactive({
  pageIndex: 1,
  pageSize: 12,
  totalCount: 0
})

// 计算属性
const isEdit = computed(() => !!route.params.id)
const packageId = computed(() => route.params.id as string)

const isFormValid = computed(() => {
  return form.name.trim() && selectedTemplates.value.length > 0
})

// 防抖搜索
const debouncedTemplateSearch = debounce(() => {
  templatePagination.pageIndex = 1
  loadAvailableTemplates()
}, 500)

// 加载优惠券包详情（编辑模式）
async function loadPackageDetail() {
  if (!isEdit.value) return

  try {
    loading.value = true

    const result = await CouponService.getPackage(packageId.value)

    if (isSuccess(result) && result.data) {
      const pkg = result.data
      form.name = pkg.name
      form.description = pkg.description || ''
      // 去除前端自定义有效期天数字段，改为编辑生效/失效时间
      form.couponTemplateIds = pkg.couponTemplateIds || []
      form.id = pkg.id

      // 保存后端字段，提交更新时原样传回
      backendFields.status = pkg.status
      backendFields.enableStatus = pkg.enableStatus
      backendFields.startTime = pkg.startTime
      backendFields.endTime = pkg.endTime
      backendFields.qrcodeUrl = pkg.qrcodeUrl
      backendFields.extraProperties = pkg.extraProperties
      backendFields.merchantId = pkg.merchantId

      // 映射到高级编辑字段
      advanced.status = pkg.status
      advanced.enableStatus = pkg.enableStatus
      advanced.qrcodeUrl = pkg.qrcodeUrl || ''
      advanced.extraProperties = pkg.extraProperties || ''
      advanced.merchantId = pkg.merchantId || ''
      advanced.startTimeLocal = toLocalInputValue(pkg.startTime)
      advanced.endTimeLocal = toLocalInputValue(pkg.endTime)

      // 加载已选择的模板详情
      await loadSelectedTemplates()
    } else {
      console.error('加载优惠券包详情失败:', result.message)
      alert('加载优惠券包详情失败：' + result.message)
      goBack()
    }
  } catch (error) {
    console.error('加载优惠券包详情出错:', error)
    alert('加载优惠券包详情失败，请稍后重试')
    goBack()
  } finally {
    loading.value = false
  }
}

// 加载已选择的模板详情
async function loadSelectedTemplates() {
  if (!form.couponTemplateIds.length) {
    selectedTemplates.value = []
    return
  }

  try {
    const templates: CouponTemplate[] = []

    for (const templateId of form.couponTemplateIds) {
      try {
        const result = await CouponService.getTemplateDetail(templateId)
        if (isSuccess(result) && result.data) {
          templates.push(result.data)
        }
      } catch (error) {
        console.error(`获取模板 ${templateId} 详情失败:`, error)
      }
    }

    selectedTemplates.value = templates
  } catch (error) {
    console.error('加载已选择模板出错:', error)
  }
}

// 加载可用的优惠券模板
async function loadAvailableTemplates() {
  try {
    templatesLoading.value = true

    const params: CouponTemplateQueryRequest = {
      pageIndex: templatePagination.pageIndex,
      pageSize: templatePagination.pageSize,
      name: templateFilters.name || undefined,
      couponType: templateFilters.couponType ? parseInt(templateFilters.couponType) : undefined,
      isActive: templateFilters.isActive === '' ? undefined : templateFilters.isActive === 'true'
    }

    const result = await CouponService.getTemplateList(params)

    if (isSuccess(result) && result.data) {
      availableTemplates.value = result.data.data || []
      templatePagination.totalCount = result.data.total || 0
    } else {
      console.error('加载优惠券模板失败:', result.message)
      availableTemplates.value = []
    }
  } catch (error) {
    console.error('加载优惠券模板出错:', error)
    availableTemplates.value = []
  } finally {
    templatesLoading.value = false
  }
}

// 切换模板页面
function changeTemplatePage(page: number) {
  templatePagination.pageIndex = page
  loadAvailableTemplates()
}

// 添加模板
function addTemplate(template: CouponTemplate) {
  if (!template.id || isTemplateSelected(template.id)) return

  selectedTemplates.value.push(template)
  form.couponTemplateIds.push(template.id)
}

// 移除模板
function removeTemplate(templateId: string) {
  selectedTemplates.value = selectedTemplates.value.filter(t => t.id !== templateId)
  form.couponTemplateIds = form.couponTemplateIds.filter(id => id !== templateId)
}

// 检查模板是否已选择
function isTemplateSelected(templateId: string): boolean {
  return form.couponTemplateIds.includes(templateId)
}

// 提交表单
async function submitForm() {
  if (!isFormValid.value || submitting.value) return

  try {
    submitting.value = true

    let result
    if (isEdit.value) {
      // 更新优惠券包
      const updateData: CouponPackageUpdateRequest = {
        id: form.id!,
        name: form.name.trim(),
        description: form.description?.trim() || undefined,
        couponTemplateIds: form.couponTemplateIds,
        // 对齐后端字段：优先使用用户编辑的值
        status: advanced.status ?? backendFields.status ?? 2,
        enableStatus: advanced.enableStatus ?? backendFields.enableStatus ?? 1,
        startTime: advanced.startTimeLocal ? toLocalTimestamp(advanced.startTimeLocal) : (backendFields.startTime ?? nowLocalTimestamp()),
        endTime: advanced.endTimeLocal ? toLocalTimestamp(advanced.endTimeLocal) : (backendFields.endTime ?? nowLocalTimestamp(365 * 24 * 3600 * 1000)),
        qrcodeUrl: advanced.qrcodeUrl || backendFields.qrcodeUrl,
        extraProperties: advanced.extraProperties || backendFields.extraProperties,
        merchantId: backendFields.merchantId
      }
      result = await CouponService.updatePackage(updateData)
    } else {
      // 创建优惠券包
      const merchantId = advanced.merchantId || (auth.user as any)?.merchantId || selectedTemplates.value[0]?.merchantId
      const createData: CouponPackageCreateRequest = {
        name: form.name.trim(),
        description: form.description?.trim() || undefined,
        couponTemplateIds: form.couponTemplateIds,
        // 后端创建必需字段
        merchantId,
        status: advanced.status ?? 2,
        startTime: advanced.startTimeLocal ? toLocalTimestamp(advanced.startTimeLocal) : nowLocalTimestamp(),
        endTime: advanced.endTimeLocal ? toLocalTimestamp(advanced.endTimeLocal) : nowLocalTimestamp(365 * 24 * 3600 * 1000)
      }
      result = await CouponService.createPackage(createData)
    }

    if (isSuccess(result)) {
      // 操作成功，返回列表页
      router.push('/coupon-packages')
    } else {
      alert(`${isEdit.value ? '更新' : '创建'}失败：` + result.message)
    }
  } catch (error) {
    console.error(`${isEdit.value ? '更新' : '创建'}优惠券包出错:`, error)
    alert(`${isEdit.value ? '更新' : '创建'}失败，请稍后重试`)
  } finally {
    submitting.value = false
  }
}

// 返回上一页
function goBack() {
  router.back()
}

// 格式化优惠券价值
function formatCouponValue(template: CouponTemplate): string {
  if (template.couponType === 1) { // 减免券
    return formatCouponAmount(template.discountAmount || 0)
  } else if (template.couponType === 2) { // 折扣券
    return formatCouponDiscount(template.discount || 0)
  }
  return '-'
}

// 格式化使用门槛
function formatThreshold(amount?: number): string {
  if (!amount || amount === 0) return '无门槛'
  return `满${formatCouponAmount(amount)}`
}

// 获取优惠券类型样式类
function getCouponTypeClass(type: number): string {
  switch (type) {
    case 1: return 'reduction'
    case 2: return 'discount'
    case 3: return 'gift'
    default: return 'default'
  }
}

// 组件挂载时初始化
onMounted(async () => {
  // 确保拿到当前用户信息，用于填充商户ID
  try {
    if (!auth.user) {
      const u = await getCurrentUser()
      if (isSuccess(u) && u.data) {
        auth.setUser(u.data)
      }
    }
    advanced.merchantId = (auth.user as any)?.merchantId || advanced.merchantId
  } catch {
    // ignore
  }
  // 加载可用模板
  await loadAvailableTemplates()
  
  // 如果是编辑模式，加载优惠券包详情
  if (isEdit.value) {
    await loadPackageDetail()
  }
})

// 仅允许通过点击按钮触发提交，屏蔽回车触发表单提交
function noop(_e?: Event) { /* no-op */ }
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.breadcrumb-link {
  color: var(--primary);
  text-decoration: none;
}

.breadcrumb-link:hover {
  text-decoration: underline;
}

.breadcrumb-separator {
  color: var(--text-secondary);
}

.breadcrumb-current {
  color: var(--text-primary);
  font-weight: 500;
}

.actions {
  display: flex;
  gap: 12px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn.primary {
  background: var(--primary);
  color: white;
}

.btn.primary:hover:not(:disabled) {
  background: var(--primary-dark);
}

.btn.secondary {
  background: var(--bg-secondary);
  color: var(--text-primary);
  border: 1px solid var(--border);
}

.btn.secondary:hover:not(:disabled) {
  background: var(--bg-tertiary);
}

.btn.danger {
  background: var(--danger);
  color: white;
}

.btn.danger:hover:not(:disabled) {
  background: var(--danger-dark);
}

.btn.sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.loading-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top: 3px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

.spinner-sm {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--border);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border);
}

.card-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.form-group label.required::after {
  content: ' *';
  color: var(--danger);
}

.form-input,
.form-textarea {
  padding: 10px 12px;
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 14px;
  background: white;
  transition: border-color 0.2s ease;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--primary);
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-hint {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.4;
}

.template-filters {
  margin-bottom: 24px;
  padding: 16px;
  background: var(--bg-secondary);
  border-radius: 6px;
}

.filter-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.filter-field {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.selected-templates {
  margin-bottom: 24px;
}

.selected-templates h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 16px 0;
}

.selected-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.selected-template {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background: var(--primary-light);
  border: 1px solid var(--primary);
  border-radius: 6px;
}

.template-info {
  flex: 1;
}

.template-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

.template-type {
  font-size: 12px;
  color: var(--text-secondary);
}

.available-templates h4 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 16px 0;
}

.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.template-card {
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 16px;
  background: white;
  transition: all 0.2s ease;
}

.template-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.template-card.selected {
  border-color: var(--primary);
  background: var(--primary-light);
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.template-header h5 {
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
  flex: 1;
}

.type-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  margin-left: 8px;
}

.type-badge.reduction {
  background: var(--success-light);
  color: var(--success);
}

.type-badge.discount {
  background: var(--info-light);
  color: var(--info);
}

.type-badge.gift {
  background: var(--warning-light);
  color: var(--warning);
}

.type-badge.default {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
}

.template-content {
  margin-bottom: 12px;
}

.template-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
}

.info-row .label {
  color: var(--text-secondary);
}

.info-row .value {
  color: var(--text-primary);
  font-weight: 500;
}

.info-row .status.active {
  color: var(--success);
}

.info-row .status.inactive {
  color: var(--warning);
}

.template-actions {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 16px;
}

.page-info {
  font-size: 14px;
  color: var(--text-secondary);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 20px 0;
  border-top: 1px solid var(--border);
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--text-secondary);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 动画效果 */
.fade-in {
  animation: fadeIn 0.3s ease-out;
}

.slide-up {
  animation: slideUp 0.4s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 16px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-row {
    grid-template-columns: 1fr;
  }
  
  .templates-grid {
    grid-template-columns: 1fr;
  }
  
  .selected-grid {
    flex-direction: column;
  }
  
  .form-actions {
    flex-direction: column-reverse;
  }
}
</style>
